package cn.sc.summer.job.service;

import cn.sc.summer.job.model.XxlJobGroup;
import cn.sc.summer.job.util.HttpClientUtil;
import com.alibaba.fastjson.JSONObject;
import cn.sc.summer.constant.project.ProjectConstant;
import cn.sc.summer.constant.util.ConvertUtil;
import cn.sc.summer.exception.enums.CommonExceptionEnum;
import cn.sc.summer.job.property.XXLProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类名：job服务实现
 *
 * @author a-xin
 * @date 2024/8/16 10:42
 */
@Slf4j
@Service
public class JobServiceImpl implements JobService {

    @Resource
    private XXLProperties xxlProperties;

    /**
     * 登录job服务并获取返回cookie信息
     *
     * @return cookie信息
     */
    @Override
    public List<Cookie> getJobCookie() {
        return getJobCookie(xxlProperties);
    }

    /**
     * 登录job服务并获取返回cookie信息
     *
     * @param xxlProperties job配置服务
     * @return cookie信息
     */
    @Override
    public List<Cookie> getJobCookie(XXLProperties xxlProperties) {
        return getJobCookie(xxlProperties.getUserName(), xxlProperties.getPassword(), xxlProperties.getClientAddress());
    }

    /**
     * 登录job服务并获取返回cookie信息
     *
     * @param userName      用户名
     * @param password      登录密码
     * @param clientAddress job服务地址
     * @return cookie信息
     */
    @Override
    public List<Cookie> getJobCookie(String userName, String password, String clientAddress) {
        Map<String, Object> params = new HashMap<>();
        params.put("userName", userName);
        params.put("password", password);
        params.put("ifRemember", "on");
        String url = clientAddress + "/login";
        CookieStore store = new BasicCookieStore();
        JSONObject resultJson = HttpClientUtil.sendPost(url, params, store);
        CommonExceptionEnum.NORMAL_EXCEPTION.exceptionIf(!resultJson.containsKey("code"), "The summer-job initialize failed!");
        CommonExceptionEnum.NORMAL_EXCEPTION.exceptionIf(!resultJson.get("code").equals(200), resultJson.getString("msg"));
        return store.getCookies();

    }

    /**
     * 向job服务注册服务组信息
     */
    @Override
    public void registerServerGroup() {
        if (checkRegister()) {
            XxlJobGroup xxlJobGroup = new XxlJobGroup();
            xxlJobGroup.setTitle(ProjectConstant.SERVER_NAME);
            xxlJobGroup.setAppname(ProjectConstant.SERVER_NAME);
            xxlJobGroup.setAddressType(0);

            Map<String, Object> xxlJob = ConvertUtil.convertToMap(xxlJobGroup, "title", "appname", "addressType");
            String clientAddress = xxlProperties.getClientAddress();
            CookieStore cookieStore = createCookieStore();
            String url = clientAddress + "/jobgroup/save";
            JSONObject resultJson = HttpClientUtil.sendPost(url, xxlJob, cookieStore);
            if (!resultJson.get("code").equals(200)) {
                log.error("==> The jobGroup:{} registered failed!", ProjectConstant.SERVER_NAME);
            }
            refreshServerGroup();
        }

    }

    /**
     * 刷新注册服务组信息
     */
    @Override
    public void refreshServerGroup() {
        String clientAddress = xxlProperties.getClientAddress();
        String url = clientAddress + "/jobgroup/refresh";
        CookieStore cookieStore = createCookieStore();
        HttpClientUtil.sendPost(url, new HashMap<>(), cookieStore);
    }

    /**
     * 校验该服务是否需要注册至job服务中
     *
     * @return 是否注册
     */
    public Boolean checkRegister() {
        Map<String, Object> params = new HashMap<>();
        params.put("appname", ProjectConstant.SERVER_NAME);

        String clientAddress = xxlProperties.getClientAddress();
        CookieStore cookieStore = createCookieStore();
        String url = clientAddress + "/jobgroup/pageList";
        JSONObject resultJson = HttpClientUtil.sendPost(url, params, cookieStore);
        return Integer.parseInt(resultJson.get("recordsFiltered").toString()) <= 0;
    }

    /**
     * 创建访问cookie凭证
     *
     * @return cookie凭证
     */
    private CookieStore createCookieStore() {
        CookieStore store = new BasicCookieStore();
        List<Cookie> jobCookie = getJobCookie();
        jobCookie.stream().forEach(store::addCookie);
        return store;
    }

}
